import { autojsExpress } from './autojsExpress'
import express from 'express'
import { readFileSync } from 'fs-extra'
import { createServer as httpCreateServer } from 'http'
import { createServer as httpsCreateServer } from 'https'
import { join } from 'path'

export function autojsServer() {
    const app = express()
    app.use((req, res, next) => {
        const origin = req.headers.origin;
        if (origin) {
            res.setHeader('Access-Control-Allow-Origin', origin); // 设置为具体的源
        } else {
            res.setHeader("Access-Control-Allow-Origin", "*");
        }
        res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, PATCH, DELETE");
        res.setHeader("Access-Control-Allow-Headers", "X-Requested-With,Content-Type,Authorization");
        (res as any).setHeader("Access-Control-Allow-Credentials", true);
        // 并且对于预检请求，直接返回200
        if (req.method === 'OPTIONS') {
            res.status(200).end();
        } else {
            next();
        }
    });
    app.use(express.json());
    app.use(express.urlencoded());
    autojsExpress(app)


    const httpServer = httpCreateServer(app)
    const httpsCertFile = join(__dirname, '../certs/server.crt')
    const httpsKeyFile = join(__dirname, '../certs/server.key')
    const httpsCert = readFileSync(httpsCertFile)
    const httpsKey = readFileSync(httpsKeyFile)
    const httpsServer = httpsCreateServer({
        cert: httpsCert,
        key: httpsKey
    }, app)

    httpServer.listen(80, '0.0.0.0', () => {
        console.log(`server start at http://0.0.0.0`)
    })
    httpsServer.listen(443, '0.0.0.0', () => {
        console.log(`server start at https://0.0.0.0`)
    })
}